//
//  SXPrefreshView.swift
//  weibo
//
//  Created by shixinPeng on 16/3/5.
//  Copyright © 2016年 shixinPeng. All rights reserved.
//

import UIKit
import SnapKit

//枚举 三种不同的状态
enum RefreshType: Int {
    //正常状态
    case Normal = 0
    //下拉状态
    case Pulling = 1
    //加载状态
    case Loading = 2
    
}
class SXPrefreshView: UIControl {
    //保存tableView
    var scrollView: UIScrollView?
    
    //记录过去的refreshView的状态
    var oldrefreshtype: RefreshType = .Normal
    
    //记录此时的状态 ,默认为普通
    var status:RefreshType = .Normal{
        didSet{
            switch status{
                //正常状态
            case .Normal:
                titleLabel.text = "下拉刷新"
                
                loadingImageView.hidden = true
                
                arrowImageView.hidden = false
                
                arrowImageView.transform = CGAffineTransformIdentity
                
                if oldrefreshtype == .Loading {//由下载调到正常
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= 30
                    })
                    
                }
         
                //释放刷新状态
            case .Pulling:
                titleLabel.text = "释放刷新"
                
                loadingImageView.hidden = true
                
                arrowImageView.hidden = false
                
                self.arrowImageView.transform = CGAffineTransformMakeRotation(-0.01)
            
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    })
                
                
                //下载状态
            case .Loading:
                //保留下载状态
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.scrollView?.contentInset.top += 30
                })
                
                titleLabel.text = "正在下载..."
                
                loadingImageView.hidden = false
                
                arrowImageView.hidden = true
                
                //发送触发事件
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
            }
            //保存值
            oldrefreshtype = status
        }
        
    }
    //下载结束,恢复原形
    func endResFreshing() {
        status = .Normal
    }

//自定义界面三部曲
    //1.重写init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //2.设置私有方法,添加控件和添加约束
    func setUpUI() {
        backgroundColor = UIColor.yellowColor()
        //设置尺寸
        self.frame = CGRectMake(0, -200,kUISCREEN_W , 200)
        
        //添加控件
        addSubview(titleLabel)
        addSubview(arrowImageView)
        addSubview(loadingImageView)
        //添加约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.bottom.equalTo(self.snp_bottom).offset(-10)
        }
        arrowImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-35)
            make.bottom.equalTo(self.snp_bottom).offset(-7)
        }
        loadingImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-35)
            make.bottom.equalTo(self.snp_bottom).offset(-7)
        }
        
        loadingImageView.hidden = false
    }
    //FIXME: 下拉刷新核心监听代码 利用KVO
    //把控件添加到父控件调用的方法,这个方法可以获取要添加到的控件,
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
     
        //newsSuperView是tableView,转为scrollView,然后设一个全局数据去接收他.
        scrollView = newSuperview as? UIScrollView
        
        //监听scrollView的值变化
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
    }
    //监听值得变化
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let scrollView = object as? UIScrollView
        
//        printLog(scrollView?.contentOffset.y)
//        
//        printLog("属性中的值:\(self.scrollView?.contentOffset.y)")
        //最基础的判断,当我们拖拽页面的时候,在去判断此时下来界面的状态
        if scrollView!.dragging {//在拖拽
            
            if scrollView?.contentOffset.y < -150 && status == .Normal{
                //改变状态为,释放刷新
                status = .Pulling
                
            } else if scrollView?.contentOffset.y < -100 && scrollView?.contentOffset.y > -150 && status == .Pulling{
                
                //正常状态,下拉刷新
                status = .Normal
            }
            }else {//手释放
                
                if scrollView?.contentOffset.y < -150 && status == .Pulling {
                //释放,下载中
                status = .Loading
                //printLog("下拉刷新---下载数据中")
          
            }
   
        }
    
    }
    //3.懒加载
    private lazy var titleLabel:UILabel = {
        
       let lab = UILabel()
        
        lab.text = "刷新界面"
        
        lab.textColor = UIColor.blackColor()
    
        lab.font = UIFont.systemFontOfSize(14)
        
        return lab
    }()
    //箭头图片的懒加载
    private lazy var arrowImageView:UIImageView = {
        
        let img = UIImageView()
        
        img.image = UIImage(named: "tableview_pull_refresh")
        
        return img
    }()
    //圈圈图片
    private lazy var loadingImageView: UIImageView = {
        
        let img = UIImageView()
        
        img.image = UIImage(named:"tableview_loading")
        
        return img
    }()
    
    deinit{//移除通知
        if let scrollView = self.scrollView {
            scrollView.removeObserver(self, forKeyPath: "contentOffset")
        }
        
        
    }
}
